//
//  SignatureSelectListController.m
//  手写签批的Demo
//
//  Created by MacBook on 2019/8/19.
//  Copyright © 2019 MacBook. All rights reserved.
//

#import "SignatureSelectListController.h"
#import "Masonry.h"
#import "ZTCraryUtils.h"
#import "ZTPPNetworkHelper.h"
#import "ZTMacros.h"
#import <MJExtension/MJExtension.h>
@interface SignatureSelectListController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *selectTbv;
@property (nonatomic, strong) NSArray *dataArray;


@end

static NSString *cellId = @"selectCell";

@implementation SignatureSelectListController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self configUI];
    [self getSignatureList];
}

- (void)configUI{
    
    self.title = @"选择签章";
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.selectTbv];
    [self.selectTbv mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11.0, *)) {
            make.edges.mas_equalTo(self.view.safeAreaInsets);
        } else {
            make.edges.mas_equalTo(self.view);
        }
    }];
}

- (UITableView *)selectTbv{
    if (!_selectTbv) {
        _selectTbv = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _selectTbv.delegate = self;
        _selectTbv.dataSource = self;
        [_selectTbv registerClass:[UITableViewCell class] forCellReuseIdentifier:cellId];
        _selectTbv.tableFooterView = [UIView new];
    }
    return _selectTbv;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexPath];
    if (self.dataArray.count > indexPath.row) {
        ZTCrazySignatureModel *model = self.dataArray[indexPath.row];
        cell.textLabel.text = model.markName;
    }
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    ZTCrazySignatureModel *model = self.dataArray[indexPath.row];
    WEAK_SELF;
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"请输入密码" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertVc addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"请输入签章密码";
        textField.secureTextEntry = YES;
    }];
    [alertVc addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }]];
    [alertVc addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        UITextField *passwordTextField = alertVc.textFields.firstObject;
        if (passwordTextField.text.length == 0) {
            [ZTCraryUtils showHudOnWindow:@"请输入密码"];
            return ;
        }
        [weakSelf loadImgWithName:model.markName password:passwordTextField.text];
        
    }]];
    [self presentViewController:alertVc animated:YES completion:nil];
}

- (void)loadImgWithName:(NSString *)markName password:(NSString *)psd{
    
    NSString *urlString = [NSString stringWithFormat:@"%@/seeyon/rest/signet/signetPic?token=%@",self.model.hostUrl,self.model.token];
    NSDictionary *paramDic = @{@"markName": markName,
                               @"password": psd,
                               @"affairId": self.model.affairId
                               };
    
    [ZTPPNetworkHelper POST:urlString parameters:paramDic success:^(id responseObject) {
        
        NSData *data = responseObject;
        if (data.length == 5) {
            [ZTCraryUtils showHudOnWindow:@"请输入正确的密码"];
            return ;
        }
        NSString *jsonString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSArray *jsonArray = [jsonString componentsSeparatedByString:@","];
        
        NSString *imageString = jsonArray[1];
        
        NSData *decodedImgData = [[NSData alloc] initWithBase64EncodedString:imageString options:NSDataBase64DecodingIgnoreUnknownCharacters];
        
        UIImage *image = [UIImage imageWithData:decodedImgData];

        if ([self.delegate respondsToSelector:@selector(getSignaturePic:)] && image!= nil) {
            [self.delegate getSignaturePic:image];
            if (self.presentingViewController) {
                
                [self dismissViewControllerAnimated:YES completion:^{}];
            }else{
                
                [self.navigationController popViewControllerAnimated:YES];
            }
        }
        
    } failure:^(NSError *error) {
        [ZTCraryUtils showHudOnWindow:@"签章获取失败"];
    }];
}

- (void)getSignatureList{
    
    NSString *urlString = [NSString stringWithFormat:@"%@/seeyon/rest/signet/signets/%@?token=%@",self.model.hostUrl,self.model.affairId,self.model.token];
    [ZTPPNetworkHelper setRequestSerializer:PPRequestSerializerJSON];
    [ZTPPNetworkHelper GET:urlString parameters:@{} success:^(id responseObject) {
        
        NSString *jsonString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSArray *jsonArray = [ZTCraryUtils convertToArrayFromString:jsonString];
        if (jsonArray.count == 0) {
            [ZTCraryUtils showHudOnWindow:@"暂无签章"];
            return ;
        }
        self.dataArray = [ZTCrazySignatureModel mj_objectArrayWithKeyValuesArray:jsonArray];
        [self.selectTbv reloadData];
    } failure:^(NSError *error) {
        [ZTCraryUtils showHudOnWindow:@"暂无签章"];
    }];
}

@end
